#!/bin/bash

# Prevent from IFS attack, set IFS to space, tab, and newline.
IFS=' 	
'
# Prevent from PATH attack, we set our path to the following place and export them.
OLDPATH="$PATH"
PATH=/bin:/usr/bin:/sbin:/usr/sbin
export PATH

# Display the user manual.
usage()
{
	echo "Usage: $PROGRAM [--all] [--?] [--help] [--version] envvar pattern(s)"
}

# Display help information and exit.
usage_and_exit()
{
	usage
	exit $1
}

error()
{
	echo "$@" 1>&2
	usage_and_exit 1
}

# Display the version information.
version()
{
	echo "$PROGRAM version $VERSION"
}

# Here we increment the exit code.
warning()
{
	echo "$@" 1>&2
	EXITCODE=`expr $EXITCODE + 1`
}

all=no
envvar=
EXITCODE=0
PROGRAM=`basename "$0"`
VERSION=1.0

while test $# -gt 0
do
	case $1 in
	--all | -a )
		all=yes
		;;
	--help | -h | '--?' | '-?')
		usage_and_exit 0
		;;
	--version | -v )
		version
		exit 0
		;;
	-*)
		error "Unrecognized option: $1"
		;;
	*)
		break
		;;
	esac
	shift 
done

envvar="$1"
test $# -gt 0 && shift
test "x$envvar" = "xPATH" && envvar=OLDPATH
# Here we evaluate the value of environment variable $envvar to 
# content like ${PATH}, then change the character ":" to space.
dirpath=` eval echo '${'"$envvar"'}' 2>/dev/null | tr : ' ' `

#sanity check
if test -z "$envvar"
then
	error "Enviroment variable missing or empty"
elif test "x$dirpath" = "x$envvar"
then
	error "Broken sh on this platform: cannot expand $envvar"
elif test -z "$dirpath"
then
	error "Empty directory search path"
elif test $# -eq 0
then
	exit 0
fi

# Do the find operation.
for pattern in "$@"
do
	result=
	for dir in $dirpath
	do
		for file in $dir/$pattern
		do
			if  test -f "$file"
			then
				result="$file"
				echo $result
				test "$all" = "no" && break 2
			fi
		done
	done
	test -z "$result" && warning "$pattern: not found"
done

# Check for exitcode for unix.
test $EXITCODE -gt 125 && EXITCODE=125
exit $EXITCODE
